package com.test.udp.file;

import com.test.udp.model.Employee;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * 文件传输
 * UDP协议发送方
 * 1.使用DatagramSocket 指定端口,创建接收端
 * 2.准备容器 封装成DatagramPacket包裹
 * 3.阻塞式接收包裹receive(DatagramPacket p)
 * 4.分析数据
 * byte[] getByte()
 * getLength()
 * 5.释放资源
 *
 * @author: ybl
 * @create: 2019-05-27 22:38
 **/
public class UDPFileServer {

    public static void main(String[] args) throws Exception {
        System.out.println("接收方启动中...");

//        1.使用DatagramSocket 指定端口,创建接收端
        DatagramSocket server = new DatagramSocket(9999);
//        2.准备容器 封装成DatagramPacket包裹,创建一个字节数组对象,长度为UDP的最大长度1024*60
        byte[] data = new byte[1024 * 60];
        DatagramPacket packet = new DatagramPacket(data, 0, data.length);
//        3.阻塞式接收包裹receive(DatagramPacket p)
        server.receive(packet); //阻塞式
//        4.分析数据
//        byte[] getByte()
//        getLength()
        byte[] bytes = packet.getData();

        ObjectInputStream oos = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(bytes)));

        Object result = oos.readObject();

        if (result instanceof Employee) {
            Employee e = (Employee) result;
            System.out.println(e);
        }

//        5.释放资源
        server.close();
    }
}
